import { createI18n } from 'vue-i18n';
import pinia from '/@/stores/index';
import { storeToRefs } from 'pinia';
import { useThemeConfig } from '/@/stores/themeConfig';
import zhcnLocale from 'element-plus/lib/locale/lang/zh-cn';
import enLocale from 'element-plus/lib/locale/lang/en';
import zhtwLocale from 'element-plus/lib/locale/lang/zh-tw';

import nextZhcn from '/@/i18n/lang/zh-cn';
import nextEn from '/@/i18n/lang/en';
import nextZhtw from '/@/i18n/lang/zh-tw';

import pagesLoginZhcn from '/@/i18n/pages/login/zh-cn';
import pagesLoginEn from '/@/i18n/pages/login/en';
import pagesLoginZhtw from '/@/i18n/pages/login/zh-tw';

import pagesFormI18nZhcn from '/@/i18n/pages/formI18n/zh-cn';
import pagesFormI18nEn from '/@/i18n/pages/formI18n/en';
import pagesFormI18nZhtw from '/@/i18n/pages/formI18n/zh-tw';

async function importAll() {
	let obj_en = {};
	let obj_zh_cn = {};
	let obj_zh_tw = {};

	let promise_arr_en: any[] = [];
	let promise_arr_zh_cn: any[] = [];
	let promise_arr_zh_tw: any[] = [];

	const modulesFiles = import.meta.glob('./pages/*/*.ts');
	for (const [key, value] of Object.entries(modulesFiles)) {
		if (key.endsWith('en.ts')) {
			promise_arr_en.push(value());
		} else if (key.endsWith('zh-cn.ts')) {
			promise_arr_zh_cn.push(value());
		} else if (key.endsWith('zh-tw.ts')) {
			promise_arr_zh_tw.push(value());
		}
	}
	let res_en = await Promise.all(promise_arr_en);
	let res_zh_cn = await Promise.all(promise_arr_zh_cn);
	let res_zh_tw = await Promise.all(promise_arr_zh_tw);

	if (res_en.length) {
		res_en.forEach((item: any) => {
			obj_en = { ...obj_en, ...item.default };
		});
	}
	if (res_zh_cn.length) {
		res_zh_cn.forEach((item: any) => {
			obj_zh_cn = { ...obj_zh_cn, ...item.default };
		});
	}
	if (res_zh_tw.length) {
		res_zh_tw.forEach((item: any) => {
			obj_zh_tw = { ...obj_zh_tw, ...item.default };
		});
	}
	return Promise.resolve({
		en: obj_en,
		zh: obj_zh_cn,
		tw: obj_zh_tw,
	});
}

const fileLang: any = await importAll();

// 定义语言国际化内容
/**
 * 说明：
 * /src/i18n/lang 下的 ts 为框架的国际化内容
 * /src/i18n/pages 下的 ts 为各界面的国际化内容
 */

const messages = {
	[zhcnLocale.name]: {
		...zhcnLocale,
		message: {
			...nextZhcn,
			// ...pagesLoginZhcn,
			// ...pagesFormI18nZhcn,
			...fileLang.zh,
		},
	},
	[enLocale.name]: {
		...enLocale,
		message: {
			...nextEn,
			// ...pagesLoginEn,
			// ...pagesFormI18nEn,
			...fileLang.en,
		},
	},
	[zhtwLocale.name]: {
		...zhtwLocale,
		message: {
			...nextZhtw,
			// ...pagesLoginZhtw,
			// ...pagesFormI18nZhtw,
			...fileLang.tw,
		},
	},
};

// 读取 pinia 默认语言
const stores = useThemeConfig(pinia);
const { themeConfig } = storeToRefs(stores);

// 导出语言国际化
// https://vue-i18n.intlify.dev/guide/essentials/fallback.html#explicit-fallback-with-one-locale
export const i18n = createI18n({
	legacy: false,
	silentTranslationWarn: true,
	missingWarn: false,
	silentFallbackWarn: true,
	fallbackWarn: false,
	locale: themeConfig.value.globalI18n,
	fallbackLocale: zhcnLocale.name,
	messages,
});
